﻿using CommandLib;
using CommandLib.Helper;
using FastSql.Core;
using LiteDB;
using SignalrChat.Models;

namespace SignalrChat.DbServer
{
    public class LiteUsersDao
    {
        private static LitedbHelper litedb;
        private static ILiteCollection<Users> liteCollection;
        static LiteUsersDao()
        {

            litedb = new LitedbHelper("userdb");
            liteCollection = litedb.GetTable<Users>("Users");
            if (liteCollection == null)
            {
                liteCollection = litedb.CreatTable<Users>("Users");
                liteCollection.EnsureIndex(e => e.Id, true);
            }
            if (liteCollection.Count() == 0)
            {
                var user = new Users()
                {
                    Id = Guid.NewGuid(),
                    Account = "admin",
                    CreateTime = DateTime.Now,
                    LoginTime = DateTime.Now,
                    NickName = "管理员",
                    PassWord = Md5Helper.MD5Encrypt("admin")

                };
                liteCollection.Insert(user);
            }
        }


        public static List<Users> GetUsers()
        {
            return liteCollection.Query().ToList();
        }

        public static Users getById(Guid Id)
        {

            return liteCollection.FindById(Id);
        }

        public static bool AddUsers(Users users)
        {
            users.Id = Guid.NewGuid();
            return liteCollection.Insert(users) != null;
        }

        public static bool UpdateUsers(Users users)
        {

            return liteCollection.Update(users.Id, users);
        }

        public static bool UpdateLoginTime(Guid Id, DateTime dateTime)
        {
            var model = liteCollection.FindById(Id);
            if (model != null)
            {
                model.LoginTime = dateTime;
                return liteCollection.Update(model);
            }
            else
            {
                return false;
            }

        }
        public static bool DeleteUsers(Guid Id)
        {
            return liteCollection.Delete(Id);

        }
    }
}
